package com.yanxu;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025-06-05-2025
 * @Description: 提供者，用于提供服务
 */
public class UDPProvider {
    public static void main(String[] args) throws IOException {
        System.out.println("UDP provider start");

        /* 创建 DatagramSocket 对象，并监听 20000 端口，用于接收数据。 */
        DatagramSocket datagramSocket = new DatagramSocket(20000);

        /* 创建 DatagramPacket, 用于接收数据 */
        byte[] buf = new byte[1024];
        DatagramPacket receivePackage = new DatagramPacket(buf, buf.length);

        /* 接收 */
        datagramSocket.receive(receivePackage);

        /* 打印接收到的信息 */
        // 发送端的ip地址
        String hostAddress = receivePackage.getAddress().getHostAddress();
        // 发送端的 port
        int port = receivePackage.getPort();
        int length = receivePackage.getLength();
        // 将接收到的数据转换为 string
        String msg = new String(buf, 0, length);
        System.out.println(hostAddress + ":" + port);
        System.out.println(msg);

        /* 收到消息之后，也回送一条消息 */
        String response = "receive data length: " + length;
        DatagramPacket datagramPacket =
                new DatagramPacket(response.getBytes(), response.getBytes().length, receivePackage.getAddress(), port);
        datagramSocket.send(datagramPacket);

        /* 释放资源 */
        datagramSocket.close();
    }
}